package com.system.framework.security.service;

import com.system.common.constant.Constants;
import com.system.common.exception.CustomException;
import com.system.common.exception.user.UserPasswordNotMatchException;
import com.system.common.utils.MessageUtils;
import com.system.common.utils.SecurityUtils;
import com.system.framework.manager.AsyncManager;
import com.system.framework.manager.factory.AsyncFactory;
import com.system.framework.security.LoginUser;
import com.system.framework.thradlocal.ContextHolder;
import com.system.module.system.domain.SysUser;
import com.system.module.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author mars
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private AuthenticationManager authenticationManager;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password, String roleId) {
        // 用户验证
        Authentication authentication = null;
        try {
            ContextHolder.setContext(roleId);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        ContextHolder.clearContext();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public void register(String username, String password, String mobile, String type) {
        SysUser sysUser = new SysUser();
        sysUser.setAvatar("");
        sysUser.setDeptId(103L);
        sysUser.setNickName(username);
        sysUser.setUserName(username);
        sysUser.setPhonenumber(mobile);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setStatus("0");
        sysUser.setSex("1");
        sysUser.setDelFlag("0");
        sysUser.setEmail("850994222@qq.com");
        if ("11".equals(type)) {
            sysUser.setRoleIds(new Long[]{2L});
        }
        if ("22".equals(type)) {
            sysUser.setRoleIds(new Long[]{100L});
        }
        sysUserService.insertUser(sysUser);


    }
}
